from __future__ import (absolute_import, division, print_function,
                        unicode_literals)
import datetime  
import os.path  
import sys
import backtrader as bt

class TestStrategy(bt.Strategy):
    params = (('exitbars', 5), ('maperiod', 15),('printlog', False),)

    def log(self, txt, dt=None):
        dt = dt or self.datas[0].datetime.date(0)
        print('%s, %s' % (dt.isoformat(), txt))

    def __init__(self):
        self.dataclose = self.datas[0].close

        self.order = None
        self.buyprice = None
        self.buycomm = None
        self.sma = bt.indicators.SimpleMovingAverage(self.datas[0], period=self.params.maperiod)

        # Indicators for the plotting show
        bt.indicators.ExponentialMovingAverage(self.datas[0], period=25)
        bt.indicators.WeightedMovingAverage(self.datas[0], period=25,
                                            subplot=True)
        bt.indicators.StochasticSlow(self.datas[0])
        bt.indicators.MACDHisto(self.datas[0])
        rsi = bt.indicators.RSI(self.datas[0])
        bt.indicators.SmoothedMovingAverage(rsi, period=10)
        bt.indicators.ATR(self.datas[0], plot=False)

    def notify_order(self, order):
        if order.status in [order.Submitted, order.Accepted]:
            return

        if order.status in [order.Completed]:
            if order.isbuy():
                self.log(
                    '买入执行，价格：%.2f，成本：%.2f，佣金 %.2f' %
                    (order.executed.price,
                     order.executed.value,
                     order.executed.comm))

                self.buyprice = order.executed.price
                self.buycomm = order.executed.comm
            else:
                self.log('卖出执行，价格：%.2f，成本：%.2f，佣金 %.2f' %
                         (order.executed.price,
                          order.executed.value,
                          order.executed.comm))
            self.bar_executed = len(self)

        elif order.status in [order.Canceled, order.Margin, order.Rejected]:
            self.log('订单取消/保证金不足/拒绝')

        self.order = None

    def notify_trade(self, trade):
        if not trade.isclosed:
            return

        self.log('利润记录，毛利润 %.2f，净利润 %.2f' %
                 (trade.pnl, trade.pnlcomm))

    def next(self):
        self.log('收盘价，%.2f' % self.dataclose[0])
        if self.order:
            return

        # if not self.position:
        #     if self.dataclose[0] < self.dataclose[-1]:
        #         if self.dataclose[-1] < self.dataclose[-2]:
        #             self.log('创建买入订单，%.2f' % self.dataclose[0])
        #             self.order = self.buy()
        # else:
        #     if len(self) >= (self.bar_executed + self.params.exitbars):
        #         self.log('创建卖出订单，%.2f' % self.dataclose[0])
        #         self.order = self.sell()

        if not self.position:
            if self.dataclose[0] > self.sma[0]:
                self.log('BUY CREATE, %.2f' % self.dataclose[0])
                self.order = self.buy()
        else:
            if self.dataclose[0] < self.sma[0]:
                self.log('SELL CREATE, %.2f' % self.dataclose[0])
                self.order = self.sell()
    
    def stop(self):
        self.log('(MA Period %2d) Ending Value %.2f' %
                 (self.params.maperiod, self.broker.getvalue()), doprint=True)

if __name__ == '__main__':
    cerebro = bt.Cerebro()
    # cerebro.addstrategy(TestStrategy, exitbars=7,maperiod=range(10, 31))
    strats = cerebro.optstrategy(TestStrategy, maperiod=range(10, 31))

    modpath = os.path.dirname(os.path.abspath(sys.argv[0]))
    datapath = os.path.join(modpath, './datas/orcl-1995-2014.txt')

    data = bt.feeds.YahooFinanceCSVData(
        dataname=datapath,
        fromdate=datetime.datetime(2000, 1, 1),
        todate=datetime.datetime(2000, 12, 31),
        reverse=False)

    cerebro.adddata(data)
    cerebro.broker.setcash(100000.0)
    cerebro.addsizer(bt.sizers.FixedSize, stake=10)
    cerebro.broker.setcommission(commission=0.001)

    print('初始投资组合价值：%.2f' % cerebro.broker.getvalue())
    cerebro.run(maxcpus=1)
    print('最终投资组合价值：%.2f' % cerebro.broker.getvalue())

    cerebro.plot()

"""
数据源推荐tushare、baostock

实盘，先不要梭哈，先用小资金验证策略，验证你搭建的系统能跑起来，这期间你会发现很多自己代码中的bug。修复bug也是反复的事情。
实盘理论上有三种办法：UI驱动、邮件或钉钉之类的通知人肉执行、接口（依赖券商给你开权限）。我用的第一种。

反思反思。你会有自己对量化的看法和经验。
最后，散户搞量化，还是要又自知之明，肯定先得有兴趣才能驱动。奋斗一阵，可能量化没挣钱，代码能力倒是练出来了。挣钱工作是个慢慢磨的过程。

"""